package luxing.common.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;

import luxing.common.service.CloudStorageService;
import luxing.constant.StorageConfig;
import net.coobird.thumbnailator.Thumbnails;

/**
 * 阿里云存储
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-03-26 16:22
 */
@Service("cloudStorageService")
@Transactional
public class CloudStorageServiceImpl implements CloudStorageService {

	private OSSClient client;

	@PostConstruct
	private void init() {
		client = new OSSClient(StorageConfig.endPoint, StorageConfig.accessKeyId, StorageConfig.accessKeySecret);
	}

	public void upload(byte[] data, String bucket, String path) {
		InputStream inputStream = new ByteArrayInputStream(data);
		client.putObject(bucket, path, inputStream);
	}

	public void uploadCompress(MultipartFile file, String bucket, String suffix, String path, String thumbPath)
			throws Exception {
		InputStream thumbInput = file.getInputStream();
		// 把图片读入到内存中
		BufferedImage thumbBufImg = ImageIO.read(thumbInput);
		// 压缩图片
		thumbBufImg = Thumbnails.of(thumbBufImg).width(300).keepAspectRatio(true).outputQuality(0.5).asBufferedImage();
		// 存储图片文件byte数组
		ByteArrayOutputStream thumbBos = new ByteArrayOutputStream();
		// 图片写入到 ImageOutputStream
		ImageIO.write(thumbBufImg, suffix, thumbBos);
		thumbInput = new ByteArrayInputStream(thumbBos.toByteArray());
		// 上传缩略图
		client.putObject(bucket, thumbPath, thumbInput);

		InputStream input = new ByteArrayInputStream(file.getBytes());
		// 上传图片
		client.putObject(bucket, path, input);

	}

	public void delete(String bucket, String path) {
		client.deleteObject(bucket, path);
	}

	public String generatePresignedUrl(String bucket, String key) {
		// 设置URL过期时间为1小时
		Date expiration = new Date(new Date().getTime() + 3600 * 1000);
		// 生成URL
		URL url = client.generatePresignedUrl(bucket, key, expiration);
		return url.toString();
	}

}
